import React, {Component} from "react";
import moment from "moment";

import {
    Form,
    Input,
    Button,
    Row,
    Col,
    Select,
    Tooltip,
    DatePicker,
    Tabs,
    Table,
    InputNumber,
    message,
    Cascader
} from "antd";
import {
    LoadingOutlined,
    PlusOutlined,
    CloseCircleOutlined,
    EyeInvisibleOutlined,
    MinusSquareOutlined,
    BellOutlined,
    EyeOutlined,
} from "@ant-design/icons";

const {Option} = Select;
const {RangePicker} = DatePicker;
const {TabPane} = Tabs;
const {Column} = Table;
const {Search} = Input;

import axios from "@src/lib/axios";

import "@src/style/product.scss";
import Operation from "@src/components/Operation";
import PageTitle from "@src/components/PageTitle";

export default class Product extends Component {
    //static contextType = ApiContext;
    formRef = React.createRef();
    state = {
        area: [],
        params: {
            page: 1,
            size: 15,
            city_id: 0,
            type_id: '',
            hotel_star_level: '',
            show: 0,
            recommend: 0,
            hotel_name: ""
        },
        hotelList: [],
        total: 0,
        loading: false,
        hotelTypeConf:[],
        hotelStarConf:[],
    };

    fetchData = () => {
        this.setState({loading: true});
        const {params} = this.state;
        axios.post("/product/hotel/list", params).then(res => {
            if (res.code === 0) {
                let data = res.data;
                this.setState({
                    hotelList: data.list,
                    total: data.total
                });
                this.setState({loading: false});
            }
        });
    };

    //获取酒店类型配置信息
    getHotelTypeConfig = () => {
        axios.post('/platform/hotel/conf/type/list').then(res => {
            if (res.code === 0) {
                let {data} = res;
                let hotelTypeConf = [];
                data.forEach(function (item) {
                    hotelTypeConf.push({"label": item.conf_name, "value": item.id})
                })
                this.setState({hotelTypeConf})
            }
        })
    }

    //获取星级配置
    getHotelStarType = () => {
        axios.post('/platform/hotel/conf/star/list').then(res => {
            if (res.code === 0) {
                let {data} = res;
                let hotelStarConf = [];
                data.forEach(function (item) {
                    hotelStarConf.push({"label": item.title, "value": item.id})
                })
                this.setState({hotelStarConf})
            }
        })
    }

    getArea = () => {
        axios.post('/area_load', { id: 7 }).then(res => {
            if (res.code === 0) {
                let data = res.data;
                console.log(data);
                this.setState({ area: data });
            }
        });


    };

    onSearchHandler = hotel_name => {
        Object.assign(this.state.params, {hotel_name});
        this.fetchData();
    };

    onValuesChange = (changedValues, allValues) => {
        console.log(changedValues, allValues);
        Object.assign(this.state.params, {...changedValues});
        this.fetchData();
    };

    onOpera = (k, row) => {
        console.log(k);
        switch (k) {
            case '0':
                this.del(row);
                break;
            case '1':
                this.toggleShow(row);
                break
            case '2':
                this.setRecommend(row);
                break
        }
    };

    toggleShow = ({show, hotel_id}) => {
        axios.post("/product/hotel/switch", {
            show: show === 1 ? 2 : 1,
            hotel_id
        }).then(res => {
            if (res.code === 0) {
                message.success("修改成功");
                this.fetchData();
            }
        });
    }

    setRecommend = ({recommend, hotel_id}) => {
        axios.post("/product/hotel/recommend", {
            recommend: recommend === 1 ? 2 : 1,
            hotel_id
        }).then(res => {
            if (res.code === 0) {
                message.success("修改成功");
                this.fetchData();
            }
        });
    }
    del = ({hotel_id}) => {
            axios.post("/product/hotel/delete", {
                hotel_id
            }).then(res => {
                if (res.code === 0) {
                    message.success("删除成功！");
                    this.fetchData();
                }
            });
        }

    toEdit = (hotel_id) => {
        this.props.history.push('/hotel/addOrEdit', {hotel_id});
    }

    UNSAFE_componentWillMount() {
        this.getArea();
        this.getHotelTypeConfig();
        this.getHotelStarType();
        this.fetchData();
    }

    changeSort(val, hotel_id) {
        console.log(val);
        if (val === '') {
            return;
        }
        axios.post("/product/hotel/set_sort", {
            hotel_id,
            sort_val: val
        }).then(res => {
            if (res.code === 0) {
                message.success("修改成功!");
            }
        });
    }

    onChangeHandler = (k, v) => {
        this.setState({[k]: v});
    };
    onChangePage = (page) => {
        this.state.params.page = page;
        this.fetchData();
    }
    onFinish = () => {
    };

    render() {
        let {params, area, hotelList, total, loading,hotelTypeConf,hotelStarConf} = this.state;
        console.log('hotelStarConf',hotelStarConf);
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(
                    `selectedRowKeys: ${selectedRowKeys}`,
                    "selectedRows: ",
                    selectedRows
                );
            },
            getCheckboxProps: record => ({
                disabled: record.name === "Disabled User", // Column configuration not to be checked
                name: record.name
            })
        };
        const hotelColumns = [
            {
                title: "酒店名称",
                width: 200,
                dataIndex: "hotel_name",
                align: "center",
                ellipsis:{showTitle:false},
                render:(hotel_name)=>{
                    return (
                        <Tooltip placement="topLeft" title={hotel_name}>
                            {hotel_name}
                        </Tooltip>
                    )
                }
            },
            {
                title: "状态",
                width: 80,
                dataIndex: "show",
                align: "center",
                render: val =>
                    val == 1 ? (
                        <EyeOutlined style={{color: "#1890ff"}}/>
                    ) : (
                        <EyeInvisibleOutlined/>
                    )
            },
            {
                title: "推荐",
                width: 80,
                dataIndex: "recommend",
                align: "center",
                render: (text, {recommend}) => recommend === 1 ? <Button type="link">是</Button> : '否'
            },
            {
                title: "排序",
                width: 80,
                dataIndex: "sort_val",
                align: "center",
                render: (val, {hotel_id}) => (
                    <InputNumber size="middle" min={1} defaultValue={val} onBlur={(v) => this.changeSort(v, hotel_id)}/>
                )
            },
            {
                title: "操作",
                width: 80,
                dataIndex: "hotel_name",
                align: "center",
                render: (e, row, index) => (
                    <div>
                        <Button type="link" onClick={() => this.toEdit(row.hotel_id)}>编辑</Button>
                        <Operation
                            options={[
                                { key: 0, name: "删除", icon: <CloseCircleOutlined /> },
                                {
                                    key: 1, name: row.show === 2 ? "显示" : "隐藏", isGrey: row.show === 2 ? false : true, icon: (
                                        row.show == 2 ? (
                                            <EyeOutlined style={{color: "#1890ff"}}/>
                                        ) : (
                                            <EyeInvisibleOutlined/>
                                        )
                                    )
                                },
                                {
                                    key: 2,
                                    name: row.recommend === 2 ? "推荐" : "不推荐",
                                    isGrey: row.recommend === 2 ? false : true,
                                    icon: <BellOutlined />
                                },
                            ]}
                            onOpera={({key}) => this.onOpera(key, row)}
                        />
                    </div>
                )
            }
        ];

        return (
            <div style={{padding: "0 15px 100px 15px", background: "#fff"}}>
                <PageTitle title="酒店列表"/>
                <Row style={{padding: "20px 0 0 0"}}>
                    <Col span={24}>
                        <Form
                            rel={this.state.formRef}
                            size="middle"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 24}}
                            name="basic"
                            initialValues={params}
                            onFinish={this.onFinish}
                            onValuesChange={this.onValuesChange}
                        >
                            <Row gutter={20}>
                                <Col span={8}>
                                    <Form.Item colon={false} label="出发城市" name="city_id">
                                        <Cascader
                                            fieldNames={{label: 'name', value: 'id', children: '_child'}}
                                            options={area}
                                            placeholder="请选择地区"
                                            expandTrigger="hover"
                                            showSearch={
                                                function filter(inputValue, path) {
                                                    return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
                                                }
                                            }
                                            changeOnSelect
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item colon={false} label="酒店类型" name="type_id">
                                        <Select options={hotelTypeConf} allowClear/>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Form.Item colon={false} label="酒店星级" name="hotel_star_level">
                                        <Select options={this.state.hotelStarConf} allowClear/>
                                    </Form.Item>
                                </Col>

                            </Row>
                            <Row gutter={20}>
                                <Col span={8}>
                                    <Form.Item colon={false} label="推荐" name="recommend">
                                        <Select>
                                            <Option value={0}>全部</Option>
                                            <Option value={1}>推荐</Option>
                                            <Option value={2}>不推荐</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>

                                <Col span={6}>
                                    <Form.Item colon={false} label="状态" name="show">
                                        <Select>
                                            <Option value={0}>所有</Option>
                                            <Option value={1}>显示</Option>
                                            <Option value={2}>隐藏</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Col span={14} align="right" style={{padding: "0 20px 0 0"}}>
                                        <Search
                                            style={{width: "200px"}}
                                            placeholder="输入酒店名称"
                                            onSearch={value => this.onSearchHandler(value)}
                                            enterButton
                                        />
                                    </Col>
                                </Col>
                            </Row>
                            <Row gutter={20}>
                                <Col span={5}>
                                    <Button type="primary" onClick={() => this.props.history.push('/hotel/addOrEdit')}><PlusOutlined />添加酒店</Button>
                                </Col>
                            </Row>
                        </Form>
                    </Col>
                </Row>

                <Table
                    size="small"
                    loading={loading}
                    // rowSelection={{
                    //     ...rowSelection
                    // }}
                    columns={hotelColumns}
                    rowKey="hotel_id"
                    dataSource={hotelList}
                    pagination={{
                        total,
                        pageSize: 15,
                        current: this.state.params.page,
                        onChange: this.onChangePage
                    }}
                />
            </div>
        );
    }
}
